package com.demo.accessibilitykeeper;

import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
import android.widget.Toast;

import java.io.IOException;
import java.util.List;

/**
 * 相机屏蔽服务
 * 功能：屏蔽前置相机，阻止面容识别和支付验证
 */
public class CameraBlockService extends Service {
    private static final String TAG = "CameraBlockService";
    
    private WindowManager windowManager;
    private SurfaceView blockingSurface;
    private Camera camera;
    private CameraManager cameraManager;
    private boolean isCameraBlocked = false;
    private String frontCameraId;
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "CameraBlockService created");
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cameraManager = (CameraManager) getSystemService(CAMERA_SERVICE);
        }
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent != null ? intent.getStringExtra("action") : null;
        
        if ("block_camera".equals(action)) {
            blockCamera();
        } else if ("unblock_camera".equals(action)) {
            unblockCamera();
        } else if ("toggle_camera".equals(action)) {
            toggleCameraBlock();
        }
        
        return START_STICKY;
    }
    
    /**
     * 屏蔽相机
     */
    public void blockCamera() {
        if (isCameraBlocked) {
            Log.d(TAG, "Camera already blocked");
            return;
        }
        
        try {
            Log.d(TAG, "🚫 BLOCKING_CAMERA - Starting camera blocking process");
            
            // 方法1：使用旧版Camera API占用相机
            blockCameraLegacy();
            
            // 方法2：使用新版Camera2 API占用相机
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                blockCamera2();
            }
            
            // 方法3：创建遮挡层
            createCameraBlockingOverlay();
            
            isCameraBlocked = true;
            
            Log.d(TAG, "✅ CAMERA_BLOCKED_SUCCESSFULLY");
            Toast.makeText(this, "相机已屏蔽，面容识别将失败", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ FAILED_TO_BLOCK_CAMERA", e);
            Toast.makeText(this, "屏蔽相机失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 恢复相机
     */
    public void unblockCamera() {
        if (!isCameraBlocked) {
            Log.d(TAG, "Camera not blocked");
            return;
        }
        
        try {
            Log.d(TAG, "🔓 UNBLOCKING_CAMERA - Restoring camera functionality");
            
            // 释放旧版Camera API
            releaseCameraLegacy();
            
            // 释放新版Camera2 API
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                releaseCamera2();
            }
            
            // 移除遮挡层
            removeCameraBlockingOverlay();
            
            isCameraBlocked = false;
            
            Log.d(TAG, "✅ CAMERA_UNBLOCKED_SUCCESSFULLY");
            Toast.makeText(this, "相机已恢复，面容识别正常工作", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ FAILED_TO_UNBLOCK_CAMERA", e);
            Toast.makeText(this, "恢复相机失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 切换相机屏蔽状态
     */
    public void toggleCameraBlock() {
        if (isCameraBlocked) {
            unblockCamera();
        } else {
            blockCamera();
        }
    }
    
    /**
     * 使用旧版Camera API占用相机
     */
    private void blockCameraLegacy() {
        try {
            Log.d(TAG, "🔧 BLOCKING_CAMERA_LEGACY_API");
            
            // 获取相机数量
            int numberOfCameras = Camera.getNumberOfCameras();
            Log.d(TAG, "Found " + numberOfCameras + " cameras");
            
            // 尝试占用所有相机
            for (int i = 0; i < numberOfCameras; i++) {
                try {
                    Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
                    Camera.getCameraInfo(i, cameraInfo);
                    
                    // 优先占用前置相机
                    if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                        Log.d(TAG, "Blocking front camera (ID: " + i + ")");
                        camera = Camera.open(i);
                        
                        // 设置预览参数
                        Camera.Parameters parameters = camera.getParameters();
                        
                        // 设置最低分辨率以减少资源占用
                        List<Camera.Size> sizes = parameters.getSupportedPreviewSizes();
                        if (sizes != null && !sizes.isEmpty()) {
                            Camera.Size smallestSize = sizes.get(sizes.size() - 1);
                            parameters.setPreviewSize(smallestSize.width, smallestSize.height);
                        }
                        
                        // 设置最低帧率
                        parameters.setPreviewFrameRate(1);
                        
                        camera.setParameters(parameters);
                        
                        // 开始预览（占用相机资源）
                        camera.startPreview();
                        
                        Log.d(TAG, "✅ Front camera blocked successfully");
                        break;
                    }
                } catch (Exception e) {
                    Log.w(TAG, "Failed to block camera " + i + ": " + e.getMessage());
                }
            }
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_BLOCKING_CAMERA_LEGACY", e);
        }
    }
    
    /**
     * 使用新版Camera2 API占用相机
     */
    private void blockCamera2() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP || cameraManager == null) {
            return;
        }
        
        try {
            Log.d(TAG, "🔧 BLOCKING_CAMERA2_API");
            
            // 获取所有相机ID
            String[] cameraIds = cameraManager.getCameraIdList();
            
            for (String cameraId : cameraIds) {
                try {
                    // 获取相机特征
                    android.hardware.camera2.CameraCharacteristics characteristics = 
                        cameraManager.getCameraCharacteristics(cameraId);
                    
                    // 检查是否为前置相机
                    Integer facing = characteristics.get(android.hardware.camera2.CameraCharacteristics.LENS_FACING);
                    if (facing != null && facing == android.hardware.camera2.CameraCharacteristics.LENS_FACING_FRONT) {
                        Log.d(TAG, "Blocking front camera (ID: " + cameraId + ")");
                        frontCameraId = cameraId;
                        
                        // 这里可以添加更复杂的Camera2 API占用逻辑
                        // 由于Camera2 API的复杂性，主要通过旧版API实现
                        break;
                    }
                } catch (CameraAccessException e) {
                    Log.w(TAG, "Failed to access camera " + cameraId + ": " + e.getMessage());
                }
            }
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_BLOCKING_CAMERA2", e);
        }
    }
    
    /**
     * 创建相机遮挡层
     */
    private void createCameraBlockingOverlay() {
        try {
            Log.d(TAG, "🔧 CREATING_CAMERA_BLOCKING_OVERLAY");
            
            // 创建遮挡Surface
            blockingSurface = new SurfaceView(this);
            blockingSurface.getHolder().addCallback(new SurfaceHolder.Callback() {
                @Override
                public void surfaceCreated(SurfaceHolder holder) {
                    Log.d(TAG, "Camera blocking surface created");
                }
                
                @Override
                public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                    Log.d(TAG, "Camera blocking surface changed: " + width + "x" + height);
                }
                
                @Override
                public void surfaceDestroyed(SurfaceHolder holder) {
                    Log.d(TAG, "Camera blocking surface destroyed");
                }
            });
            
            // 设置窗口参数
            WindowManager.LayoutParams params = new WindowManager.LayoutParams();
            
            // 设置窗口类型
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            } else {
                params.type = WindowManager.LayoutParams.TYPE_PHONE;
            }
            
            // 设置窗口标志
            params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                         WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                         WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH |
                         WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS;
            
            // 设置窗口格式
            params.format = PixelFormat.TRANSLUCENT;
            
            // 设置窗口大小和位置
            params.width = 1; // 最小尺寸
            params.height = 1; // 最小尺寸
            params.gravity = Gravity.TOP | Gravity.LEFT;
            
            // 添加到窗口管理器
            windowManager.addView(blockingSurface, params);
            
            Log.d(TAG, "✅ Camera blocking overlay created");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_CREATING_CAMERA_BLOCKING_OVERLAY", e);
        }
    }
    
    /**
     * 释放旧版Camera API
     */
    private void releaseCameraLegacy() {
        try {
            if (camera != null) {
                Log.d(TAG, "🔓 RELEASING_CAMERA_LEGACY_API");
                camera.stopPreview();
                camera.release();
                camera = null;
                Log.d(TAG, "✅ Camera legacy API released");
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_RELEASING_CAMERA_LEGACY", e);
        }
    }
    
    /**
     * 释放新版Camera2 API
     */
    private void releaseCamera2() {
        try {
            if (frontCameraId != null) {
                Log.d(TAG, "🔓 RELEASING_CAMERA2_API");
                frontCameraId = null;
                Log.d(TAG, "✅ Camera2 API released");
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_RELEASING_CAMERA2", e);
        }
    }
    
    /**
     * 移除相机遮挡层
     */
    private void removeCameraBlockingOverlay() {
        try {
            if (blockingSurface != null && windowManager != null) {
                Log.d(TAG, "🔓 REMOVING_CAMERA_BLOCKING_OVERLAY");
                windowManager.removeView(blockingSurface);
                blockingSurface = null;
                Log.d(TAG, "✅ Camera blocking overlay removed");
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_REMOVING_CAMERA_BLOCKING_OVERLAY", e);
        }
    }
    
    /**
     * 检查相机是否被屏蔽
     */
    public boolean isCameraBlocked() {
        return isCameraBlocked;
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "CameraBlockService destroyed");
        
        // 清理相机资源
        if (isCameraBlocked) {
            unblockCamera();
        }
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
